#!/usr/bin/env node

/**
 * EndoSight-UC 系统完整工作流程测试
 * 测试文件上传、AI推理、评分结果
 */

import fetch from 'node-fetch';
import FormData from 'form-data';
import fs from 'fs';
import path from 'path';

const API_BASE = 'http://localhost:4000/api';
const TEST_IMAGE = 'colonoscopy_2024_01_15_patient001.jpg';

// 测试配置
const TEST_CONFIG = {
    maxRetries: 3,
    timeout: 30000,
    adminCredentials: {
        username: 'admin',
        password: 'admin123'
    }
};

let authToken = '';

// 工具函数
async function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function makeRequest(url, options = {}) {
    const response = await fetch(url, {
        timeout: TEST_CONFIG.timeout,
        ...options
    });

    const data = await response.json();
    return { response, data };
}

// 1. 测试用户登录
async function testLogin() {
    console.log('🔐 测试用户登录...');

    try {
        const { response, data } = await makeRequest(`${API_BASE}/auth/login`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(TEST_CONFIG.adminCredentials)
        });

        if (data.success && data.data.token) {
            authToken = data.data.token;
            console.log('✅ 登录成功');
            console.log(`   Token: ${authToken.substring(0, 20)}...`);
            return true;
        } else {
            console.log('❌ 登录失败:', data.message);
            return false;
        }
    } catch (error) {
        console.log('❌ 登录请求失败:', error.message);
        return false;
    }
}

// 2. 测试文件上传和AI评分
async function testFileUploadAndScoring() {
    console.log('📤 测试文件上传和AI评分...');

    if (!authToken) {
        console.log('❌ 未获取到认证token');
        return false;
    }

    if (!fs.existsSync(TEST_IMAGE)) {
        console.log(`❌ 测试图像不存在: ${TEST_IMAGE}`);
        return false;
    }

    try {
        // 创建表单数据
        const form = new FormData();
        form.append('file', fs.createReadStream(TEST_IMAGE));
        form.append('patient_id', '1');
        form.append('clinical_text', '55岁男性患者，反复腹痛腹泻3月，肠镜检查显示结肠黏膜轻度充血水肿，UCEIS评分评估');

        const { response, data } = await makeRequest(`${API_BASE}/scoring/submit`, {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${authToken}`,
                ...form.getHeaders()
            },
            body: form
        });

        if (data.success) {
            console.log('✅ 文件上传成功');
            console.log(`   任务ID: ${data.data.task_id}`);
            console.log(`   状态: ${data.data.status}`);

            // 等待AI处理完成
            console.log('⏳ 等待AI处理...');
            await sleep(3000);

            // 获取评分结果
            return await testScoringResult(data.data.task_id);
        } else {
            console.log('❌ 文件上传失败:', data.message);
            console.log(`   错误代码: ${data.error_code}`);
            return false;
        }
    } catch (error) {
        console.log('❌ 文件上传请求失败:', error.message);
        return false;
    }
}

// 3. 测试评分结果
async function testScoringResult(taskId) {
    console.log('📊 测试评分结果查询...');

    try {
        const { response, data } = await makeRequest(`${API_BASE}/scoring/result/${taskId}`, {
            headers: {
                'Authorization': `Bearer ${authToken}`,
                'Content-Type': 'application/json'
            }
        });

        if (data.success) {
            console.log('✅ 评分结果查询成功');
            console.log(`   UCEIS评分: ${data.data.score}`);
            console.log(`   严重程度: ${data.data.severity}`);
            console.log(`   置信度: ${data.data.confidence}`);
            console.log(`   AI处理时间: ${data.data.ai_inference_time}`);
            return true;
        } else {
            console.log('❌ 评分结果查询失败:', data.message);
            return false;
        }
    } catch (error) {
        console.log('❌ 评分结果查询失败:', error.message);
        return false;
    }
}

// 4. 测试历史记录
async function testScoringHistory() {
    console.log('📜 测试评分历史记录...');

    try {
        const { response, data } = await makeRequest(`${API_BASE}/scoring/list`, {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${authToken}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                page: 1,
                limit: 10
            })
        });

        if (data.success) {
            console.log('✅ 历史记录查询成功');
            console.log(`   总记录数: ${data.data.total}`);
            console.log(`   当前页记录数: ${data.data.items.length}`);

            if (data.data.items.length > 0) {
                console.log('   最新记录:');
                const latest = data.data.items[0];
                console.log(`     - 任务ID: ${latest.task_id}`);
                console.log(`     - 提交时间: ${latest.submit_time}`);
                console.log(`     - 状态: ${latest.status}`);
            }

            return true;
        } else {
            console.log('❌ 历史记录查询失败:', data.message);
            return false;
        }
    } catch (error) {
        console.log('❌ 历史记录查询失败:', error.message);
        return false;
    }
}

// 5. 测试AI服务健康状态
async function testAIHealth() {
    console.log('🤖 测试AI服务健康状态...');

    try {
        const { response, data } = await makeRequest(`${API_BASE}/ai/health`);

        if (data.success) {
            console.log('✅ AI服务健康');
            console.log(`   状态: ${data.data.status}`);
            console.log(`   响应时间: ${data.data.response_time}ms`);
            return true;
        } else {
            console.log('❌ AI服务不健康:', data.message);
            return false;
        }
    } catch (error) {
        console.log('❌ AI服务检查失败:', error.message);
        return false;
    }
}

// 主演示函数
async function runCompleteWorkflowTest() {
    console.log('🎯 开始EndoSight-UC完整工作流程测试\n');

    const results = {
        login: false,
        aiHealth: false,
        uploadAndScoring: false,
        history: false,
        overall: false
    };

    try {
        // 1. 测试AI服务
        results.aiHealth = await testAIHealth();
        console.log('');

        // 2. 测试登录
        results.login = await testLogin();
        console.log('');

        if (results.login) {
            // 3. 测试文件上传和AI评分
            results.uploadAndScoring = await testFileUploadAndScoring();
            console.log('');

            // 4. 测试历史记录
            results.history = await testScoringHistory();
            console.log('');
        }

        // 计算总体结果
        const passedTests = Object.values(results).filter(Boolean).length;
        const totalTests = Object.keys(results).length - 1; // 排除overall
        results.overall = passedTests === totalTests;

        // 输出测试结果
        console.log('📋 测试结果汇总:');
        console.log(`   AI服务健康: ${results.aiHealth ? '✅ 通过' : '❌ 失败'}`);
        console.log(`   用户登录: ${results.login ? '✅ 通过' : '❌ 失败'}`);
        console.log(`   文件上传和AI评分: ${results.uploadAndScoring ? '✅ 通过' : '❌ 失败'}`);
        console.log(`   历史记录查询: ${results.history ? '✅ 通过' : '❌ 失败'}`);
        console.log(`   总体结果: ${results.overall ? '✅ 全部通过' : '❌ 部分失败'}`);
        console.log(`   通过率: ${passedTests}/${totalTests} (${Math.round(passedTests/totalTests*100)}%)`);

        if (results.overall) {
            console.log('\n🎉 EndoSight-UC系统工作流程测试完全成功！');
        } else {
            console.log('\n⚠️ EndoSight-UC系统存在问题，需要进一步调试');
        }

    } catch (error) {
        console.log('💥 测试过程中发生未预期错误:', error.message);
        results.overall = false;
    }

    return results;
}

// 执行测试
if (import.meta.url === `file://${process.argv[1]}`) {
    runCompleteWorkflowTest()
        .then(results => {
            process.exit(results.overall ? 0 : 1);
        })
        .catch(error => {
            console.error('测试执行失败:', error);
            process.exit(1);
        });
}

export { runCompleteWorkflowTest };